<template>


	<el-button v-on:click="addData">新增</el-button>
	
	
	<el-table :data="categoryArray" row-key="category_id">
		<el-table-column label="分类名称" prop="category_name"></el-table-column>
		<el-table-column label="分类图片地址" >
			<template #default="scope">
				 <el-image style="width: 50px; height: 50px" :src="scope.row.pic" />
			</template>
			
		</el-table-column>
		<el-table-column label="状态" >
			<template #default="scope">
				<span v-if="scope.row.status==1">
					<el-button type="primary">正常</el-button>
				</span>
				<span v-else-if="scope.row.status==0">
					<el-button type="danger">下线</el-button>
				</span>
			</template>
		</el-table-column>
		<el-table-column label="排序号" prop="seq"></el-table-column>
		<el-table-column label="操作">
			<template #default="scope">
				<el-button type="primary" v-on:click="updateCategory(scope.row)">修改</el-button>
				<el-button type="danger" v-on:click="deleteCategory(scope.row.category_id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>
	
	

	  <el-dialog
	    v-model="dialogVisible"
	    :title="dialogTitle"
	    width="500"	   
	  >
	    <el-form :model="categoryObject" label-width="auto" style="max-width: 600px">
				<el-form-item label="分类名称">
				  <el-input v-model="categoryObject.category_name" />
				</el-form-item>
			   <el-form-item label="排序号">
				 <el-input-number v-model="categoryObject.seq"></el-input-number>
			   </el-form-item>
			   <el-form-item label="分类图片">
				
				 
				 <!-- 
				  <el-input v-model="categoryObject.pic" />
				 action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
					后端的文件上传的URL地址 http://localhost:8089/FileUploadLoadController/uploadFile
					:before-upload="beforeAvatarUpload"表示文件上传前执行的函数，在此函数中可以限制上传的文件类型，文件大小 等
					 :on-success="handleAvatarSuccess"表示上传成功后的回调函数，在此函数中接收服务端的返回结果
					 
				  -->
				  
				 <el-upload
				     class="avatar-uploader"
				     action="http://localhost:8089/FileUploadLoadController/uploadFile"
				     :show-file-list="false"
					 name="photo"
				     :on-success="handleAvatarSuccess"
				     :before-upload="beforeAvatarUpload"
				   >
				   <!-- 用于预览图片的img -->
				     <img v-if="imageUrl" :src="imageUrl" class="avatar" />
				     <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
				   </el-upload>
				 
			   </el-form-item>
			   <el-form-item label="状态">
			   		<el-radio-group v-model="categoryObject.status"> 
			   		      <el-radio :value="0" size="large">下线</el-radio>
			   		      <el-radio :value="1" size="large">正常</el-radio>
			   		</el-radio-group>
			   </el-form-item>
			   <el-form-item label="上级类别">
				   <el-cascader
				         v-model="parent_id" 
				         :options="cascaderData"
				         :props="cascaderProp"
				         @change="cascaderChange"
				       />
			   </el-form-item>
	    </el-form>
		
		
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button type="primary" @click="saveCategory">
	          保存
	        </el-button>
	      </div>
	    </template>
	  </el-dialog>
	
	
</template>

<script setup>
	import {ref,onMounted,getCurrentInstance} from 'vue'
	import {ElMessage,ElMessageBox } from 'element-plus'
	
	let categoryArray = ref([])//服务端返回的树形结构数据
	
	
	let categoryData = [];//保存递归处理后的结果（将树形结构的数据转换为平行结构数据）
	
	function diGui(ca){   //遍历目录   File
		for(let i=0;i<ca.length;i++){
			categoryData.push(ca[i]);
			if (ca[i].children.length>0){
				diGui(ca[i].children);
			}
		}
	}
	
	
	let dialogTitle = ref("新增")
	
	let {proxy} = getCurrentInstance()
	
	
	let initData = ()=>{
		proxy.$axios.get("/CategoryController/queryCategoryByTree")
			.then((serverData)=>{
				console.log("服务端返回的数据为:",serverData)
				console.log("产品分类数据为:",serverData.data.data)
				if(serverData.data.code==0){
					categoryArray.value = serverData.data.data;//把服务端返回的分类数据赋给ref包装的数组
					cascaderData.value = serverData.data.data;
					console.log("服务端返回的数据为:",categoryArray.value)
					diGui(categoryArray.value)//把服务端返回的树形结果数据做为方法的参数
					console.log("处理完成后的数据结果为:",categoryData)
				}else{
					ElMessage({message:serverData.data.msg,type:"error"})
				}
			}).catch((error)=>{
				console.log("请求发生异常,原因",error)
			})
	}

	//let proxy = getCurrentInstance().proxy
	onMounted(()=>{
		//发送异步请求 
		initData();
	})
	
	
	 /*private Integer category_id;//	bigint(20) unsigned
	    private Integer  shop_id;//	bigint(20)
	    private Integer parent_id;//	bigint(20) unsigned
	    private String category_name;//	varchar(50)
	    private String icon;//	varchar(255)
	    private String pic;//	varchar(300)
	    private Integer seq;//	int(5)
	    private Integer status;//	int(1)
	    private Date rec_time;//	datetime
	    private Integer grade;//	int(2)
	    private Date update_time;//	datetime*/
			
	let categoryObject = ref({
		"category_id":null,
		"parent_id":0,
		"category_name":"",
		"shop_id":1,
		"pic":"",
		"seq":1,
		"grade":0,
		"status":1
		
	})
	
	let dialogVisible = ref(false);//用于控制对话框的显示与隐藏
	let addData = ()=>{
		dialogVisible.value = true; //控制diloag的显示
		dialogTitle.value = "新增"
		categoryObject.value = {
		"category_id":null,
		"parent_id":0,
		"category_name":"",
		"shop_id":1,
		"pic":"",
		"seq":1,
		"grade":0,
		"status":1
		
	}
		
		
		
	}
	let saveCategory = ()=>{
		//http://localhost:8088/CategoryController/addCateGory?parent_id=0&category_name=%E6%B5%8B%E8%AF%95&shop_id=1&pic=pic&seq=
		console.log("发送给后端的数据为:",categoryObject.value)
		let url = "/CategoryController/addCateGory"
		if (dialogTitle.value=='修改'){
			url = "/CategoryController/updateCateGory"
		}
		proxy.$axios.get(url,{params:categoryObject.value})
			.then((serverData)=>{
				console.log("服务端返回的数据为:",serverData)
				console.log("产品分类数据为:",serverData.data.data)
				if (serverData.data.code==0){
					initData();//重新加载数据
					dialogVisible.value = false;//隐藏dialog
				}else{
					
					ElMessage({type:"error",message:serverData.data.msg})
				}
			
			}).catch((error)=>{
				console.log("请求发生异常,原因",error)
			})
	}
	
	
	let deleteCategory= (id)=>{
		//1.询问用户是否确定要删除该记录
		//2.点击确定后发请求给后端，传递当前要删除的类别编号
		//3.后端在业务逻辑层，判断该类别下是否存在子类别，如果存在，则不允许删除，返回一个错误消息
		//4.如果删除成功，则刷新表格数据
		
		
		ElMessageBox.confirm(
			"是否确定删除该类别?",
			"提示",
			{
			  confirmButtonText: '确认',
			  cancelButtonText: '取消',
			  type: 'warning',
			}
		).then(()=>{
			
			proxy.$axios.get("/CategoryController/deleteCategory",{params:{category_id:id}})
				.then((serverData)=>{
					if (serverData.data.code==0){
						initData()
						ElMessage({type:"success",message:"删除成功"})
					}else{
						ElMessage({type:"error",message:serverData.data.msg})
					}
					
				}).catch((error)=>{
					ElMessage({type:"error",message:error.message})
				})
		})
	}
	
	
	
	
	
	
	//************级联选择组件相关变量*****************
	let parent_id = ref([]);
	let cascaderData = ref();
	let  cascaderProp = {
		  //expandTrigger: 'hover' as const
		  value:'category_id',
		  label:'category_name',
		  checkStrictly:true
	};
	
	let  cascaderChange = (value) => { //当级联选择项发生变量会，该函数会传递一个对象  格式为： {0: 85, 1: 93, 2: 119}
			
			let endValue = "";
			for(let a in value){
				console.log("对象的属性为:",a);
				//取对象的属性值: 1 对象名.属性名      2 对象名[属性名]
				endValue = value[a];
				
			}
			console.log("当前选中的项的分类编号为:",endValue);
			categoryObject.value.parent_id = endValue;
	}
	

	//*************修改数据相关的代码**************************
	
	function findParents(array){
		
		
		//取出数组中的第一个元素（类别编号），再找出这个类别的父类别，把父类别编号放到传入的数组中
		console.log("递归方法传入的参数值为:",array)
		
		//[ 85, 93 ,119,]
		let category_id = array[0];
		for(let i=0;i<categoryData.length;i++){
			if (categoryData[i].category_id==category_id && categoryData[i].parent_id!=0){
				array.unshift(categoryData[i].parent_id);
				findParents(array);
			}
		}
		/*for(let i=0;i<categoryArray.value.length;i++){
			if (categoryArray.value[i].category_id==category_id){
				if (categoryArray.value[i].parent_id>0){
					array.unshift(categoryArray.value[i].parent_id)
				}
				//当前元素的元素父的编号如果不为0，则要递归，否则结束
			//	if (categoryArray.value[i].parent_id==0)
			}else{
				console.log("xxx",categoryArray.value[i].children)
				if (categoryArray.value[i].children.length>0){
					for(let k=0;k<categoryArray.value[i].children.length;k++){
						if (categoryArray.value[i].children[k].category_id==category_id){
							array.unshift(categoryArray.value[i].children[k].parent_id)
						//	findParents(array)
						}
						
					}
				}
			}
		}*/
		
	}
	
	
	let updateCategory = (row)=>{
		dialogVisible.value = true;
		dialogTitle.value = "修改"
		parent_id.value=[];
		
		console.log(row)
		
		if (row.parent_id>0){ //判断如果有父类别，应该将父和和父类别的父类别编号放到数组中
			//parent_id.value  =[row.parent_id, row.category_id]
			//当前拿到的类别编号是119
			//以下数组中存储的元素值应该是  	[93 ,119]
			let idArray = [row.parent_id];
			
			console.log("递归前的结果为:",idArray)
			findParents(idArray)
			
			console.log("递归后的结果为:",idArray)
			parent_id.value = idArray;
			
		}else{
			//parent_id.value=[row.category_id]//选中一级类别的情况
		}
		
		
		categoryObject.value.category_name = row.category_name
		categoryObject.value.parent_id = row.parent_id
		categoryObject.value.pic = row.pic
		categoryObject.value.grade = row.grade
		categoryObject.value.seq = row.seq
		categoryObject.value.status = row.status
		categoryObject.value.shop_id = row.shop_id
		categoryObject.value.category_id = row.category_id
		
		
	}
	
	
	/*文件上传相关的变量和函数*/
	let handleAvatarSuccess = (response,uploadFile) => {
		console.log("文件上传成功后的第一个参数信息为:",response);
		console.log("文件上传成功后的第二个参数信息为:",uploadFile);
		//imageUrl.value = URL.createObjectURL(uploadFile.raw!)
		if (response.code==0){ 
			imageUrl.value = response.data;
			categoryObject.value.pic=response.data;
		} else{
			ElMessage({type:"error",message:response.msg})
		}
	}
	let beforeAvatarUpload = (rawFile) => {
		//  image/jpeg
		//  image/png
		console.log("在文件上传前执行函数传入的参数信息为:",rawFile)
		  if (rawFile.type.indexOf("image")==-1) {
			ElMessage.error('只能选择图片文件')
			return false
		  } else if (rawFile.size / 1024 / 1024 > 20) {
			ElMessage.error('不允许上传大于20M的图片!')
			return false
		  }
		  return true
		}
	let imageUrl = ref("");//代表图片路径
	
	
	
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>